package com.lei.yohuo001java;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.PointF;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.widget.NestedScrollView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.dao.green.db.DaoMaster;
import com.dao.green.db.DaoSession;
import com.lei.mvp_retrofitlibrary.http.bean.GoodsBean;
import com.lei.mvp_retrofitlibrary.mvp.view.BaseActivity;
import com.lei.yohuo001java.bean.GoodsEntiy;
import com.lei.yohuo001java.contract.ShopContract;
import com.lei.yohuo001java.one_fragment.AFragment;
import com.lei.yohuo001java.sandbox.PayResult;
import com.lei.yohuo001java.sandbox.util.OrderInfoUtil2_0;
import com.youth.banner.Banner;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Main2Activity extends BaseActivity implements ShopContract.XiangView {
    private TextView aFragTv1;
    private TextView aFragTv2;
    private Button act2Bt1;
    private RadioButton act2Rb1;
    private RadioButton act2Rb2;
    private Button act2Bt2;
    private boolean flag = false;

    private ImageView backBgIv;
//    private ImageView backIconIv;
    private LinearLayout titleLayout;
    private NestedScrollView mScrollView;

    private final float MAX_HAND_SPAN = 600f;
    private Banner bannerIv;
    private float bannerHeight = SizeUtils.dp2px(400);
    private TextView moreText;
    //moreText 在 scroll view中到位置
    private int moreTextPosition;

    //----------自定义scroll滑动---------
    private PointF startScrollPoint;
    private boolean isScrollContent = true;
    //计算手势加速度
    private VelocityTracker tracker = VelocityTracker.obtain();
    private boolean isRunTacker;
    private LinearLayout.LayoutParams params;




    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID = "2016102700769935";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static final String PID = "";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static final String TARGET_ID = "";

    /**
     *  pkcs8 格式的商户私钥。
     *
     * 	如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 	使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * 	RSA2_PRIVATE。
     *
     * 	建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 	工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCGgbycKrk+qenrIqL5ttDII+BPZcVY8YQlF7pSxsxAVn+QpmzMp5+5xfaIanzmfN4gyzTAlWOLFYtVmobUZd+Ul6017/is7gMY6hb0efk4A7nMVsTj0ExAV7+7mVKqe/KBQuhhemvb6hBnbOIjsMI2qCS0EWCio0RNR8FpWIqk60+LU43YLjMn/O2m2Ducrw3eb2qoeGUW2mlGLKwP1TIzYTMZAnpBgnT+74sUc3mTvJRPMtZ11g2NqGfDkKyGrk76si+3MBGsAxrF1eabFfJAv0oQPW4ajzxxyBaUl9HlWKUgfTqkgb5sUkj1lhNxGO7IekAnKTOLT6qrQKuuGHOjAgMBAAECggEAVhMh8sH4Z5xuYBV7O9f8xYcH3WdgIen0SZRknOIxBR8VZSjLSTAfq89+U4/pu8m+kDfZ2z/+QpwX3UEU9Uj4CewCYRjfBzMM8l2jMPH5RRpFRPll5+99TFObE98rIoRNDOEXOoIQEdw4gScRlAtiTX3OdxkDwTA/3kCECfkqSByEldet0ohuQhwV08UQcWt9FCpN6ZfSIvx7sUmZn/Y92kwOBvat4h9/W1rsLFuRi/vhRDVSdplB2eGkka0APYpv6tZmflqzTHV+nMScVJwhENN+bn0yEy/Uq/9T14FzinoXcNFM3s5B+ngzvJYD83tqyPtzFS24WMSx5q74TflLgQKBgQDuBubz1K5F2see7GrKnOvD2X2n4n+0F/CYUmUVqWzuZ4TNK83F6WYFoSNYPHJK9hNBGVFDg/p/Y7cAnyovO74xkZZhIlHxwVOqvxquLqXQEoE7gs1Yv0oYHWwxwhnR9//MITnZNgrVDoNMhEv6+LmE3kDgKZj3GUshtU66dYKfQQKBgQCQqcYMDisLaOs0P+BGz4dU4wDTRfnjspcHOanqfipPLuzMQwNXbcD/rKYU1AOcszNAeGf7da7+HLyeMwKVhdBiCY8kWH2lNHkUgxCAD1wewapRUbxhm01+QZhOoCydCPVKS8Lr8GbaXs1qhOW3Z+OukksHEwOyuLvGruA0LWL94wKBgEa+OmoBrgII8gdj0KGDXfcJbvU0tiu6acF7y5tSjZOVpLyt5iyKH85QhAa3gGiTFknk0mg0k4DFDCDdLVZ4dSCaWo1n+97UTJ+UyMM4DgP3W/1p9MoJoGXmaL+pJq9m+9mZjm3mR/XmqFNXhpWC0vCQdcup0VKva8sK7ekw/6+BAoGARyN1xM/i0wWRRGx0+d1sC45mBX9P120nX+I3cJ0CaVYGFJyPtBrA4fog4fUwoYpuFbIgUEQa/dNb3d/v0V+wjcVtos3xW6BmOnQJVTA4eNd7zemH3eflP8U6BNA3oDGbjiGbhTL/ITulgFBCNuLb0CkYxC3Rj73QeW/dyUrYd0kCgYAPf09KCzBt5NYxhI4TmMvmGymSObbz9PAGCvxOoX1uCIawDZw815l5efXfZioSCt0nosI8KCeHctSX+UR/1LskUvyoozJ7tMLnsRHI3vZR9TTUa8Qosie12wYhan3ICLh/snsDnohWTJT9fDmLQEp7fqbSc27klRGNTTsmYmT/Nw==";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;




    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(Main2Activity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(Main2Activity.this, "支付失败" + payResult, Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };



    /**
     * 支付宝支付业务示例
     */
    public void payV2(String money,String goodsname) {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            Toast.makeText(this, "注意参数", Toast.LENGTH_SHORT).show();
            return;
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2,money,goodsname);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(Main2Activity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }




    @Override
    public int bindlayout() {
        return R.layout.activity_main2;
    }

    @Override
    public void initView() {
        backBgIv = (ImageView) findViewById(R.id.fragment_good_detail_bg);
//        backIconIv = (ImageView) findViewById(R.id.fragment_good_detail_icon);
        titleLayout = (LinearLayout) findViewById(R.id.fragment_good_title_layout);
        mScrollView = (NestedScrollView) findViewById(R.id.fragment_good_detail_scroll);
        bannerIv = (Banner) findViewById(R.id.fragment_good_detail_banner);
        moreText = (TextView) findViewById(R.id.fragment_good_more_text);
        aFragTv1 = (TextView) findViewById(R.id.a_frag_tv1);
        aFragTv2 = (TextView) findViewById(R.id.a_frag_tv2);
        act2Bt1 = (Button) findViewById(R.id.act2_bt1);
        act2Rb1 = (RadioButton) findViewById(R.id.act2_rb1);
        act2Rb2 = (RadioButton) findViewById(R.id.act2_rb2);
        act2Bt2 = (Button) findViewById(R.id.act2_bt2);
        titleLayout.setAlpha(0);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initData() {
        mScrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                //标题栏值区间
//                LogUtils.d("scrollY:" + scrollY + "---" + moreTextPosition);
                if (scrollY > MAX_HAND_SPAN) {
                    showWhiteTitle(1f);
                    showBannerStyle(0);
                } else if (scrollY == 0) {
                    showWhiteTitle(0);
                    showBannerStyle(1f);
                } else {
                    showWhiteTitle(scrollY / MAX_HAND_SPAN);
                    showBannerStyle(1 - scrollY / MAX_HAND_SPAN);
                }
            }
        });
        //设置Banner初始大小
        params = (LinearLayout.LayoutParams) bannerIv.getLayoutParams();
        params.height = (int) bannerHeight;
        bannerIv.setLayoutParams(params);
        //设置moreText初始大小
        final LinearLayout.LayoutParams moreTextParams = (LinearLayout.LayoutParams) moreText.getLayoutParams();
        moreTextParams.height = SizeUtils.dp2px(100);
        moreText.setLayoutParams(moreTextParams);

        moreText.post(new Runnable() {
            @Override
            public void run() {
                //屏幕高度 - 状态栏高度 - BottomBar高度
                int index = ScreenUtils.getAppScreenHeight() - SizeUtils.dp2px(70);
                moreTextPosition = (int) (moreText.getBottom() - 0.3 * bannerHeight - index);
            }
        });
        // ---------------
        startScrollPoint = new PointF();
        mScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    startScrollPoint.x = event.getX();
                    startScrollPoint.y = event.getY();
                } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    float indexY = startScrollPoint.y - event.getY();
                    //下拉计算  当前滑动位置，小于moreText置顶都位置 +SizeUtils.dp2px(50) 添加偏移计算
                    if (mScrollView.getScrollY() + indexY < moreText.getTop() + SizeUtils.dp2px(50) && !isScrollContent) {
                        LogUtils.d("当前滑动位置，小于moreText置顶都位置");
                        mScrollView.scrollTo(0, moreText.getTop());
                        isRunTacker = false;
                    } else {
                        isRunTacker = true;
                        mScrollView.scrollTo(0, mScrollView.getScrollY() + (int) indexY);
                    }
                    startScrollPoint.y = event.getY();
//                    LogUtils.d(mScrollView.getScrollY() + "---" + moreTextPosition);

                    //TODO 还原值有问题
                    if (mScrollView.getScrollY() < moreTextPosition) {
                        isScrollContent = true;
                    }
                    tracker.addMovement(event);
                    //加速度值 1/s 1000/s
                    tracker.computeCurrentVelocity(1000);


                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (mScrollView.getScrollY() > moreTextPosition && mScrollView.getScrollY() < moreTextPosition + 200) {
                        LogUtils.d("未达到打开详情阀值，回弹");
                        scrollAnim(moreTextPosition);
                    } else if (mScrollView.getScrollY() > moreTextPosition + 200 && isScrollContent) {
                        //不是每次都触发
                        LogUtils.d("打开下部分详情");
                        scrollAnim(moreText.getBottom());
                        isScrollContent = false;
                    } else if (mScrollView.getScrollY() <= moreText.getTop() + SizeUtils.dp2px(50) && !isScrollContent) {
                        LogUtils.d("从下部分，打开上部分详情");
                        scrollAnim(moreTextPosition - moreText.getHeight());
                        isScrollContent = true;
                    }
                    if (tracker.getYVelocity() != 0 && isRunTacker) {
                        // trackerScrollAnim(tracker.getYVelocity());
                    }
                }
                return true;
            }
        });


        Intent intent = getIntent();
        GoodsBean.DataBean extra = (GoodsBean.DataBean) intent.getSerializableExtra("banner_zy");
        Log.e("ljl", "initData: "+extra.toString() );
        List<String> banners = new ArrayList<>();
        for (int i = 0; i < extra.getSmallImages().size(); i++) {
            banners.add(extra.getSmallImages().get(i));
        }
        AFragment.BannerLun(bannerIv,banners);
        aFragTv2.setText("￥"+extra.getZkFinalPrice());
        aFragTv1.setText(extra.getTitle()+"");
        act2Bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //调用支付
                payV2(extra.getZkFinalPrice(),extra.getCategoryName());
            }
        });


        DaoMaster.DevOpenHelper goods_sql = new DaoMaster.DevOpenHelper(this, "goods_sql");
        SQLiteDatabase writableDatabase = goods_sql.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(writableDatabase);
        DaoSession daoSession = daoMaster.newSession();

        act2Bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                flag = false;
                if (SPUtils.getInstance().getBoolean("log")){
                    List<GoodsEntiy> goodsEntiys = daoSession.loadAll(GoodsEntiy.class);
                    for (int i = 0; i < goodsEntiys.size(); i++) {
                        if (goodsEntiys.get(i).getTitle().equals(extra.getTitle())){
                            GoodsEntiy goodsEntiy = new GoodsEntiy(goodsEntiys.get(i).getId(),
                                    goodsEntiys.get(i).getPicturl(),
                                    goodsEntiys.get(i).getTitle(),
                                    goodsEntiys.get(i).getPrice(),
                                    goodsEntiys.get(i).getSelect_num()+1,
                                    goodsEntiys.get(i).getSelect());
                            daoSession.update(goodsEntiy);
                            flag = true;
                        }
                    }
                    if (!flag){
                        GoodsEntiy goodsEntiy = new GoodsEntiy(null,extra.getPictUrl(),extra.getTitle()
                                ,Double.parseDouble(extra.getReservePrice()),1,false);
                        daoSession.insert(goodsEntiy);
                    }

                    showToast("添加成功");
                }else {
                    Toast.makeText(Main2Activity.this, "添加失败,请先登录", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(Main2Activity.this,LoginActivity.class));
                }
            }
        });
        act2Rb1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(Main2Activity.this, "功能尚未开发", Toast.LENGTH_SHORT).show();
            }
        });
        act2Rb2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(Main2Activity.this, "功能尚未开发", Toast.LENGTH_SHORT).show();

            }
        });
        backBgIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    public void scrollAnim(int endY) {
        ValueAnimator animator = ValueAnimator.ofInt(mScrollView.getScrollY(), endY);
        animator.setDuration(200);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mScrollView.scrollTo(0, (Integer) animation.getAnimatedValue());
            }
        });
        animator.start();
    }

    public void trackerScrollAnim(float velocityY) {
        float index = -velocityY;
        if (velocityY > 40000)
            index = 40000;
        if (velocityY < -40000)
            index = -40000;
        ValueAnimator animator = ValueAnimator.ofInt(mScrollView.getScrollY(), mScrollView.getScrollY() + (int) (2100 * index / 40000f));
        animator.setDuration((long) (3000 * Math.abs(index / 40000f)));
        animator.setInterpolator(new DecelerateInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mScrollView.scrollTo(0, (Integer) animation.getAnimatedValue());
            }
        });
        animator.start();
    }

    @Override
    public void showWhiteTitle(float percent) {
        titleLayout.setAlpha(percent);
        if (percent == 0) {
//            backIconIv.setImageTintList(ColorStateList.valueOf(0xFFFFFFFF));
        }
        if (percent == 1) {
//            backIconIv.setImageTintList(ColorStateList.valueOf(0xFF000000));
        }
        backBgIv.setAlpha(1 - percent);
    }

    @Override
    public void showBannerStyle(float percent) {
        params.height = (int) (bannerHeight * 0.7 + 0.3 * bannerHeight * percent);
        bannerIv.setLayoutParams(params);
    }

    @Override
    public void hideMoreContent() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (tracker != null) {
            tracker.recycle();
            tracker = null;
        }
    }

    @Override
    public void showLayout() {

    }

    @Override
    public void hideLayout() {

    }

    @Override
    public void showToast(String msg) {
        Toast.makeText(this, ""+msg, Toast.LENGTH_SHORT).show();
    }
}
